package com.zwb.service.controller;

import com.zwb.service.common.CacheConstant;
import com.zwb.service.pojo.Department;
import com.zwb.service.service.IDepartmentService;
import com.zwb.service.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 头发又黑又长
 * @Date 2022/9/6 10:26
 * @email zwb15083976291@163.com
 */
@Api(tags = "部门管理")
@RestController
@CacheConfig(cacheNames = CacheConstant.CACHEABLE_VALUE_3_DAT)
@RequestMapping("/system/basic/department")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;


    @Cacheable(key = "'allDepartments'")
    @ApiOperation("获取所有部门")
    @GetMapping("/")
    public R<List<Department>> getAllDepartments() {
        List<Department> departments = departmentService.getAllDepartments();
        return R.success(departments);

    }

    @CacheEvict(key = "'allDepartments'")
    @ApiOperation("添加部门")
    @PostMapping("/")
    public R addDepartment(@RequestBody Department department) {
        return departmentService.addDepartment(department) ? R.success("添加部门成功") : R.error("添加部门失败");
    }

    @CacheEvict(key = "'allDepartments'")
    @ApiOperation("删除部门")
    @DeleteMapping("/{id}")
    public R delDepartment(@PathVariable("id") Integer id) {
        Integer result = departmentService.delDepartment(id);
        R r = null;
        if (result == -1) {
            r = R.error("该部门下存在员工，删除失败");
        } else if (result == -2) {
            r = R.error("该部门下存在子部门或不存在，删除失败");
        } else if (result == 0) {
            r = R.error("该部门不存在，删除失败");
        } else {
            r = R.success("删除成功");
        }
        return r;
    }
}
